

package com.hcloud.auth.audit.handler;

import com.hcloud.auth.audit.service.LoginLogService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * 登录失败后记录日志
 *
 * @author hepangui
 * @date 2018/11/29
 */
@Slf4j
@Component
@AllArgsConstructor
public class LoginFailureHandler implements ApplicationListener<AbstractAuthenticationFailureEvent> {
    private final LoginLogService loginLogService;

    /**
     * 处理登录事件处理，记录日志
     */
    @Override
    public void onApplicationEvent(AbstractAuthenticationFailureEvent event) {
        var authentication = (Authentication) event.getSource();
        var exception = event.getException();
        var principal = authentication.getPrincipal();
        var account = (String) principal;
        var msg = transferMsg(exception);
        loginLogService.saveErrorLog(account, msg);
        log.info("用户：{} 登录失败，原因是：{}", account, msg);
    }

    private String transferMsg(AuthenticationException exception) {
        if (exception instanceof BadCredentialsException) {
            return "密码错误";
        }
        if (exception instanceof LockedException) {
            return "帐号被禁用";
        }
        return exception.getMessage();
    }
}
